package com.bd.volkswagen.controller;//package com.bd.scm.module.qywx.controller;

/**
 * @ClassName WXLoginController
 * @Description TODO
 * @Author YH
 * @Date 2019/4/16 9:32
 * @Version 1.0
 **/

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bd.scm.domain.models.user.UserDaZhong;
import com.bd.scm.module.qywx.thread.TokenThread;
import com.bd.scm.module.user.service.IDtUserService;
import com.bd.scm.module.utils.WxJSUtil;
import com.bd.scm.module.utils.wx.WXAuthUtil;
//import com.bd.scm.module.visitor.VisitorService;
import com.bd.utils.vo.Result;
import com.bd.utils.wechat.WeChatUtil;
import com.bd.wx.core.util.GOauth2Core;
import com.bd.wx.core.util.WeiXinParamesUtil;

import com.bd.wx.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Map;

@RestController
@RequestMapping("/wXLogin")
public class WXLoginController{

    public static Logger log = LoggerFactory.getLogger(WXLoginController.class);

    public static String accessToken = "";

    @Autowired
    private IDtUserService iDtUserService;

//    @Autowired
//    private VisitorService visitorService;

    /**
     * 接入微信服务
     *
     */
//    @Autowired
//    private WechatService wechatService;

    @RequestMapping(value = "/dd")
    @ResponseBody
    public String dd(){
        return "调用成功";
    }

    /**
     * 微信消息接收和token验证
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/verify")
    public void weChat(HttpServletRequest request, HttpServletResponse response) throws IOException {
       System.out.println("进入");
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        PrintWriter print;
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && WeChatUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            // 进入post聊天处理
            System.out.println("enter post");
            print = response.getWriter();
            // 接收消息并返回消息
            // 调用核心服务类接收处理请求
            String respXml = ""; //wechatService.processRequest(request, response);
            print.print(respXml);
            print.flush();
            print.close();
        }
    }


    /**
     * 公众号微信登录授权
     *
     * @param request
     * @param response
     * @return
     * @throws ParseException
     * @parameter
     */
    @GetMapping("wxLogin")
    public void wxLogin(HttpServletRequest request,
                        HttpServletResponse response)
            throws ParseException, IOException {
        //JSONObject userInfo = (JSONObject) request.getSession().getAttribute("userInfo");
        String APPID = WXAuthUtil.APPID;

//        if(null !=userInfo){
//            return "redirect:https://blog.csdn.net/qq_37165674/article/details/77680202";//必须重定向，否则不能成功
//        }else {
        //这个url的域名必须要进行再公众号中进行注册验证，这个地址是成功后的回调地址
        String backUrl = WXAuthUtil.backUrl;
        // 第一步：用户同意授权，获取code
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID
                + "&redirect_uri=" + URLEncoder.encode(backUrl)
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";

        log.info("forward重定向地址{" + url + "}");
        response.sendRedirect(url);
        //return "redirect:" + url;//必须重定向，否则不能成功
//        }
    }

    /**
     * 公众号微信登录授权回调函数
     *
     * @param modelMap
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     * @parameter
     */
    @GetMapping("callBack")
    public void callBack(ModelMap modelMap, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
         * start 获取微信用户基本信息
         */
        String code = req.getParameter("code");
        //第二步：通过code换取网页授权access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WXAuthUtil.APPID
            + "&secret=" + WXAuthUtil.APPSECRET
            + "&code=" + code
            + "&grant_type=authorization_code";

        /*jsonObject:{ "access_token":"ACCESS_TOKEN","expires_in":7200,"refresh_token":"REFRESH_TOKEN","openid":"OPENID","scope":"SCOPE"}*/
        JSONObject jsonObject = WXAuthUtil.doGetJson(url);
        log.info("获取凭证:" + jsonObject.toJSONString());
        if (jsonObject == null || "".equals(jsonObject) || jsonObject.containsKey("errcode")) {
            log.debug("认证失败__网页授权获取access_token失败");
            //return "网页授权获取access_token失败";
        }

        /*openid 唯一值*/
        String openid = jsonObject.getString("openid");
        /*access_token 凭证*/
        String access_token = jsonObject.getString("access_token");
        /*refresh_token 刷新凭证*/
        String refresh_token = jsonObject.getString("refresh_token");

//        //数据库中查询是否绑定微信平台账号
//        UserLoginInfoDto userAppSearchDto = wechatService.getUserByWeiXinID(openid);
//        //标记 1:未绑定 0:绑定
//        String mark = "0";
//        //对openid加密
//        String encode = CryptUtils.encode(openid);
//        if (userAppSearchDto == null) {
//            // 尚未绑定账号
//            log.info("尚未绑定账号.....");
//            mark = "1";
//        }
//        req.getSession().setAttribute("userAppSearchDto", userAppSearchDto);
//        // 登录成功
//        resp.sendRedirect("http://192.168.2.215:8080/#/login/" + encode + "_" + mark);
        //return "redirect:http://192.168.2.215:8080/#/login/" + encode + "_" + mark;
        //第五步验证access_token是否失效；展示都不需要
        String chickUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;

        JSONObject chickuserInfo = WXAuthUtil.doGetJson(chickUrl);
        log.info("查看access_token是否失效:" + chickuserInfo.toJSONString());
        if (!"0".equals(chickuserInfo.getString("errcode"))) {
            // 第三步：刷新access_token（如果需要）-----暂时没有使用,参考文档https://mp.weixin.qq.com/wiki，
            String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + openid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
            /*refreshInfo:{ "access_token":"ACCESS_TOKEN","expires_in":7200,"refresh_token":"REFRESH_TOKEN","openid":"OPENID","scope":"SCOPE" }*/
            JSONObject refreshInfo = WXAuthUtil.doGetJson(refreshTokenUrl);
            log.info("刷新access_token:" + chickuserInfo.toJSONString());
            access_token = refreshInfo.getString("access_token");
        }

        // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
            + "&openid=" + openid
            + "&lang=zh_CN";
        JSONObject userInfo = WXAuthUtil.doGetJson(infoUrl);
        if (userInfo == null || "".equals(userInfo)) {
            log.debug("获取用户微信信息失败");
        }

        /*
         {    "openid":" OPENID",
            " nickname": NICKNAME,
            "sex":"1",
            "province":"PROVINCE"
            "city":"CITY",
            "country":"COUNTRY",
            "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
            "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
            "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" 唯一
            }
         */
        //session保存
        JSONObject user = null; //this.visitorService.getVistor(userInfo.getString("openid"));
        if(user!=null) {
            user.put("openid",userInfo.getString("openid"));
            req.getSession().setAttribute("user", user);
            resp.sendRedirect(WXAuthUtil.frontPath + "HelloWorld");
        }else{
            /*
             * end 获取微信用户基本信息
             */
            //获取到用户信息后就可以进行重定向，走自己的业务逻辑了。。。。。。
            //接来的逻辑就是你系统逻辑了
            resp.sendRedirect(WXAuthUtil.frontPath + "?openid="+userInfo.getString("openid"));
        }
    }

    private static String[] excludeSearchArr = new String[] { "page", "pageSize", "dir", "sort" };// 搜索排除值



    //企业微信正式员工验证登陆
    @GetMapping("qywxVerifyLogin")
    public Result qywxVerifyLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Result result = null;
        JSONObject map = new JSONObject();
        String UserID="";
        String code = request.getParameter("code");
        if (!"authdeny".equals(code)) {
            String access_token = TokenThread.accessToken.getToken();
            // agentid 跳转链接时所在的企业应用ID 管理员须拥有agent的使用权限；agentid必须和跳转链接时所在的企业应用ID相同
            try {
                UserID = GOauth2Core.GetUserID(access_token, code, WeiXinParamesUtil.getProperty("agentId"));
            } catch (Exception e) {
                log.info(e.getMessage());
            }
        }
        boolean falg = false;
        int i = this.iDtUserService.fingUserWxCount(UserID);
        UserDaZhong userInfo = iDtUserService.getUserInfoByUserNo(UserID);
        int isConfirm = 0;
        if(ObjectUtil.isNotNull(userInfo)) {
            falg = true;
            log.info("---confirm: {}", userInfo.getIsConfirm());
            isConfirm = ObjectUtil.isNull(userInfo.getIsConfirm()) ? 0 : userInfo.getIsConfirm();
            log.info("---confirm: {}", userInfo.getIsConfirm());
        }
        map.put("success",true);
        map.put("weChatId",UserID);//企业微信账号为空  企业微信验证失败
        map.put("falg",falg);//true 直接进入主页  false进入登录页面
        map.put("isConfirm", isConfirm);
        result = Result.ok(map);
        return result;
    }

    /**
     * 企业微信正式员工自主登陆
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("qywxLogin")
    public JSONObject qywxLogin(String weChatId, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        return this.iDtUserService.getUserByWeChatId(weChatId,request);
    }

    /**
     * 企业微信正式员工自主登陆
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("userIdLogin")
    public JSONObject userIdLogin(String userId, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        return this.iDtUserService.getUserByUserId(userId,request);
    }

    /**
     * 微信正式员工登陆
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("doLogin")
    public JSONObject doLogin(String username,String password,String weChatId, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        // 设置首页的农历日期
        Calendar ca = Calendar.getInstance();
        int year = ca.get(Calendar.YEAR);// 获取年份
        int month = ca.get(Calendar.MONTH) + 1;// 获取月份
        int day = ca.get(Calendar.DATE);// 获取日
        return this.iDtUserService.getwXUserByAccountAndPsw(username, password,"", weChatId,request);
    }

    /**微信公众号
     * 获取签名算法
     */
    @GetMapping("getSign")
    public synchronized JSONObject getSign(HttpServletRequest request,
                                          HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        String url = request.getParameter("webUrl");
        System.out.println("url=" +url);
        Map<String, String> ret = WxJSUtil.jsAPisign(url);
        System.out.println("map=" + ret.toString());
        jsonObject.put("weixin", ret);
        jsonObject.put("success",true);
        String jsonString = JSON.toJSONString(ret);
        System.out.println("getSign" + jsonString);
        return jsonObject;
    }

    /**企业微信
     * 获取签名算法
     */
    @GetMapping("getQySign")
    public synchronized JSONObject getQySign(HttpServletRequest request,
                                           HttpServletResponse response) throws Exception  {
        JSONObject jsonObject = new JSONObject();
        String url = request.getParameter("webUrl");
        System.out.println("url=" +url);
        Map<String, String> ret = WxJSUtil.jsQyAPisign(url);
        System.out.println("map=" + ret.toString());
        jsonObject.put("weixin", ret);
        jsonObject.put("success",true);
        String jsonString = JSON.toJSONString(ret);
        System.out.println("getQySign" + jsonString);
        return jsonObject;
    }
}
